<?php

namespace app\admin\service;

use app\common\model\commonModel;
use app\common\model\trUser;
use app\common\util\ErrorCode;
use app\common\util\Tools;
use Qcloud\Cos\Client;
use think\facade\Env;

/**
 * Class Auth
 * @package app\admin\service
 * 核销员服务类
 */
class VerifierService
{
    private $returnData;
    private $field = [
        "nickname" => "require", "gender" => "1", "mobile" => "require", "email" => NULL, "id_card" => NULL, 
        "prefix" => "86", "status" => 2, "remark" => ""
    ]; //填入数据库需要存储的表字段
    private $fieldMsg = ["nickname" => "核销员昵称", "mobile" => "手机号", "id_card" => "身份证号"];
    private $data = [];
    private $params;
    private $mall_id = 0;

    public function __construct($data, $params){
        $this->returnData = $data;
        $this->params = $params;
        $this->mall_id = request()->mallData["id"];
    }

    // 通过excel导入核销员数据
    public function toImportByExcel(){
        if (empty($this->params['address'])) {
            return ErrorCode::code("params_not_exist", "address");
        }
        $this->params["address"] = urldecode($this->params["address"]);
        //导入需要的字段
        $ruleData = ["nickname" => "核销员", "gender" => "性别(1男;2女)", "mobile" => "手机号", "email" => "邮箱"];
        $type = strtolower(pathinfo($this->params['address'], PATHINFO_EXTENSION));
        if($type=='xlsx'){
            $type=   'Excel2007';
        }elseif($type=='csv'){
            $type='csv';
        }else{
            $type='Excel5';
        }
        if(request()->server("IS_SCF")) {
            $cosConfig = config("thirdConfig.QCloudConfig");
            $cosClientObject = new Client([
                'region' => $cosConfig["region"], #地域，如ap-guangzhou,ap-beijing-1
                'credentials' => array('secretId' => $cosConfig["secretId"], 'secretKey' => $cosConfig["secretKey"]),
            ]);
            try {
                $targetDir = substr($this->params["address"], strpos($this->params["address"], "://")+3);
                $targetDir = substr($targetDir, strpos($targetDir, "/")+1);
                $result = $cosClientObject->getObject(array('Bucket' => $cosConfig["bucket"], 'Key' => $targetDir));
                $cosClientObject->deleteObject(array('Bucket' => $cosConfig["bucket"], 'Key' => $targetDir));
            } catch (\Exception $e) {
                Tools::writeLog("{$targetDir}导入核销员报错了：".var_export($e->getMessage(),1).var_export($this->params,1), "verifier.txt");
            }
            if (!empty($result['Body'])) {
                $this->params["address"] = "/tmp/import_excel".time(). ".$type";
                file_put_contents($this->params["address"], $result['Body']->__toString());
            }else{
                return ErrorCode::code("customized", "导入模板数据是空的");
            }
        }

        include_once Env::get("extend_path") . "/phpExcel/PHPExcel.php";
        $objReader = \PHPExcel_IOFactory::createReader($type);
        $objPHPExcel = $objReader->load($this->params['address']);
        $keys = $rows = [];
        $j = 0;
        foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
            foreach ($worksheet->getRowIterator() as $row) {
                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false);
                $k = 0;
                foreach ($cellIterator as $cell) {
                    if (!is_null($cell)) {
                        if($row->getRowIndex() == "1"){
                            if(!empty($cell->getCalculatedValue()))
                                $keys[] = Tools::remove_xss($cell->getCalculatedValue());
                        }else {
                            if(isset($keys[$k])) {
                                $rows[$j][$keys[$k]] = Tools::remove_xss($cell->getCalculatedValue());
                                $k++;
                            }
                        }
                    }
                }
                $j++;
            }
            break; //只打印第一个工作表
        }

        if(!empty($rows)) {
            $res = array_diff($ruleData, $keys);
            if (!empty($res)) {
                return ErrorCode::code("customized", "导入模板有误，缺少\"" . implode(",", $res) . "\"等列数据");
            }
            foreach ($rows as $k => $item) {
                if(empty($item[$ruleData["nickname"]]) && empty($item[$ruleData["mobile"]])){
                    continue;
                }
                $data["add_time"] = time();
                $data["mall_id"] = $this->mall_id;
                foreach ($ruleData as $field => $name) {
                    if($this->field[$field] === 'require' && empty($item[$name])){
                        return ErrorCode::code("params_not_exist", $this->fieldMsg[$field]);
                    }
                    $data[$field] = $item[$name];
                }
                $result = commonModel::toAdd(verifierTable, $data);
                if (isset($result["code"])) {
                    return $result;
                }
                if (!$result) {
                    $this->returnData = ErrorCode::$errorCode["fail"];
                }
            }
            return $this->returnData;
        }else{
            return ErrorCode::code("customized", "导入模板数据是空的");
        }
    }

    // 下载模板
    public function toExportByExcel(){
        $address = Env::get("extend_path") . "/verifier_export.xlsx";
        if (!file_exists($address)) {
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "该模板文件不存在";
            return $this->returnData;
        }
        $filename = basename($address);
        if(request()->server("IS_SCF")) {
            $returnData["returnFile"] = [
                "header" => ["Content-type" => "application/octet-stream", "Content-Disposition" => "attachment; filename=" . $filename, 'Accept-Ranges' => 'bytes'],
                "content" => file_get_contents($address)
            ];
            return $returnData;
        }else {
            header("Content-type: application/octet-stream");
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            header("Content-Length: " . filesize($address));
            readfile($address);
        }
    }

    // 获取核销员数据的分页列表
    public function getList()
    {
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;
        //搜索条件
        $filter = array(["mall_id", "=", $this->mall_id]);
        if (isset($this->params['name'])) {
            if(is_numeric($this->params['name'])){
                $filter[] = ['mobile', 'like',  "%".$this->params["name"] . "%"];
            }else {
                $filter[] = ['nickname', 'like', "%".$this->params["name"] . "%"];
            }
        }
        $data = commonModel::getList(verifierTable, "*", $filter, $page, $pageSize);
        if (!$data["data"]) {
            $this->returnData['data'] = ['list' => [], 'totalPage' => $page, 'currentPage' => $page, 'count' => 0];
        } else {
            foreach ($data["data"] as &$item){
                if(!empty($item["addTime"])) {
                    $item["addTime"] = date("Y-m-d H:i:s", $item["addTime"]);
                }
            }
            $this->returnData['data'] = ['list' => $data['data'], 'totalPage' => $data['last_page'], 'currentPage' => $data['current_page'], 'count' => $data['total']];
        }
        return $this->returnData;
    }

    // 添加核销员
    public function toAdd()
    {
        foreach ($this->field as $k => $v) {
            $ks = parse_name($k); //转换字段，变驼峰
            if ($v === 'require' && !isset($this->params[$ks])) {
                $this->returnData = ErrorCode::code("params_not_exist", $this->fieldMsg[$k]);
                return $this->returnData;
            }
            $this->data[$k] = isset($this->params[$ks]) ? $this->params[$ks] : $v;
        }
        $userModel = new trUser();
        if(!empty($this->params["userId"])) { // 代表是从用户列表里跳过来，需要绑定用户
            $data = $userModel->getFields("mobile,openid", ["id" => $this->params["userId"]], true, false);
            $userModel->doUpdate(["user_type" => 2], ["id" => $this->params["userId"]]);
            $this->data["openid"] = $data['openid'];
            $this->data["mobile"] = $data['mobile'];
        }else{
            $userData = $userModel->getFields("id,openid,user_type", ["mobile" => $this->data["mobile"], "mall_id" => $this->mall_id], true, false);
            if(!empty($userData["openid"]) && $userData["userType"] != "1") {
                $this->data["openid"] = $userData["openid"];
                $userModel->doUpdate(["user_type" => 2], ["id" => $userData["id"]]);
            }
        }
        $this->data["mall_id"] = $this->mall_id;
        $this->data["add_time"] = time();
        $result = commonModel::toAdd(verifierTable, $this->data);
        if (isset($result["code"])) {
            return $result;
        }
        if (!$result) {
            $this->returnData = ErrorCode::$errorCode["fail"];
        }
        return $this->returnData;
    }

    // 更新核销员
    public function toUpdate()
    {
        if (empty($this->params['id'])) {
            return ErrorCode::code("params_not_exist", "id");
        }
        foreach ($this->field as $k => $v) {
            $ks = parse_name($k); //转换字段，变驼峰
            if ($v === 'require' && !isset($this->params[$ks])) {
                $this->returnData = ErrorCode::code("params_not_exist", $this->fieldMsg[$k]);
                return $this->returnData;
            }
            if (isset($this->params[$ks])) {
                $this->data[$k] = $this->params[$ks];
            }
        }
        $result = commonModel::toUpdate(verifierTable, $this->data, ["id" => $this->params["id"], "mall_id" => $this->mall_id]);
        if (isset($result["code"])) {
            return $result;
        }
        if (!$result) {
            $this->returnData = ErrorCode::$errorCode["fail"];
        }
        return $this->returnData;
    }

    // 核销员的详细内容
    public function getDetail()
    {
        if (empty($this->params['id'])) {
            return ErrorCode::code("params_not_exist", "id");
        }
        $data = commonModel::getFields(verifierTable, "*", ["id" => $this->params["id"], "mall_id" => $this->mall_id]);
        if(!empty($data["addTime"])){
            $data["addTime"] = date("Y-m-d H:i:s", $data["addTime"]);
        }
        if(!empty($data["addTime"])){
            $data["addTime"] = date("Y-m-d H:i:s", $data["addTime"]);
        }
        $this->returnData["data"] = $data;
        return $this->returnData;
    }

    // 更新核销员上下线状态
    public function toUpdateStatus(){ //状态：1正常-上线；2休息-下线；3注销
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "核销员ID");
        }
        if(!isset($this->params["status"])){
            return ErrorCode::code("params_not_exist", "核销员状态");
        }
        if(!in_array($this->params["status"], [1,2])){
            return ErrorCode::code("params_error", "核销员状态");
        }
        $this->data["status"] = $this->params["status"];
        $result = commonModel::toUpdate(verifierTable, $this->data, ["id" => $this->params["id"], "mall_id" => $this->mall_id]);
        if(isset($result["code"])) {
            return $result;
        }
        if(!$result){
            $this->returnData = ErrorCode::$errorCode["fail"];
        }
        return $this->returnData;
    }

    // 删除核销员
    public function toDel()
    {
        if (empty($this->params['id'])) {
            return ErrorCode::code("params_not_exist", "id");
        }
        $data = commonModel::getFields(verifierTable, "openid", ["id" => $this->params["id"], "mall_id" => $this->mall_id]);
        $result = commonModel::delById(verifierTable, $this->params['id']);
        if (isset($result["code"])) {
            return $result;
        }
        if (!$result) {
            $this->returnData = ErrorCode::$errorCode['fail'];
            $this->returnData["msg"] = "删除失败";
        }else{
            $userModel = new trUser();
            $userModel->doUpdate(["user_type" => "0"], ["openid" => $data["openid"]]); // 删除成功后把用户核销员身份删除
        }
        return $this->returnData;
    }
}